package com.cosytek.farmmanager;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.cosytek.farmmanager.data.Farm;
import com.cosytek.farmmanager.data.FarmSummary;
import com.cosytek.farmmanager.data.Main;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MainFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainFragment extends Fragment implements ServerRequest.IServerRequestListener, AdapterView.OnItemClickListener {

    private static final String TAG = "MainFragment";
    private OnFragmentInteractionListener mListener;
    private static final String PATH_LOAD_MAIN ="/loadMain";
    private static final String PATH_LOAD_FARM ="/loadFarm";

    private Main main;

    private Activity mParent;
    private LayoutInflater layoutInflater;

    private View mProgressForm;
    private View mMainForm;
    private View viewNoFarmText;

    private ListView viewFarmList;

    private MainFragmentFarmAdapter farmListAdapter;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     * @return A new instance of fragment MainFragment.
     */
    public static MainFragment newInstance() {
        MainFragment fragment = new MainFragment();
        Bundle b = new Bundle();
        fragment.setArguments(b);
        return fragment;
    }

    public MainFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        layoutInflater = inflater;
        View v = inflater.inflate(R.layout.fragment_main, container, false);
        mMainForm = v.findViewById(R.id.frag_main_form);
        mProgressForm = v.findViewById(R.id.common_progress_form);

        mMainForm.setVisibility(View.GONE);

        viewNoFarmText = v.findViewById(R.id.frag_main_all_farm_no_farm);
        viewFarmList = (ListView)v.findViewById(R.id.frag_main_all_farm_list);

        viewFarmList.setOnItemClickListener(this);
        attemptLoadData();
        return v;
    }

    private void attemptLoadData() {
        mProgressForm.setVisibility(View.VISIBLE);

        String token = ((MainActivity)mParent).getToken();
        ServerRequest request = ServerRequest.newGetRequest(this, token, PATH_LOAD_MAIN);
        request.setTag("main");
        request.execute();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mParent = activity;
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        mParent = null;
        layoutInflater = null;
    }

    @Override
    public void onRequestCompleted(ServerRequest r,boolean success, ServerError error, String respBody) {
        mProgressForm.setVisibility(View.GONE);
        mMainForm.setVisibility(View.VISIBLE);

        if (mParent == null) {
            return;
        }

        if (success) {
            String tag = r.tag();
            switch (tag) {
                case "main":
                    initMainForm(respBody);
                    break;
                case "farm":
                    Farm f = main.onFarmLoaded(respBody);
                    if (f == null) {
                        return;
                    }

                    showFarmFragment(f.getId());
                    break;
            }

            return;
        }

        if (error != null) {
            UIHelper.promptError(mParent, error);
        }
    }

    private void initMainForm(String respBody) {
        if (respBody == null || respBody.length() < 1) {
            return;
        }

        Log.d(TAG, respBody);

        try {
            JSONObject jsonObject = new JSONObject(respBody);
            if (main == null) {
                main = Main.createFromJSONObject(jsonObject);
            } else {
                main.refreshFromJSONObject(jsonObject);
            }
            refreshUI();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void refreshUI() {
        if (main == null) {
            return;
        }

        if (farmListAdapter == null) {
            farmListAdapter = new MainFragmentFarmAdapter(main, layoutInflater);
            viewFarmList.setAdapter(farmListAdapter);
        } else {
            farmListAdapter.updateData(main);
        }

        if (main.getFarmSummaryCount() > 0) {
            viewFarmList.setVisibility(View.VISIBLE);
            viewNoFarmText.setVisibility(View.GONE);
        } else {
            viewFarmList.setVisibility(View.GONE);
            viewNoFarmText.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FarmSummary fs = main.getFarmSummary(position);
        String farmId = fs.getId();
        Farm f = main.getFarm(farmId);

        if (f == null || f.isDataExpired()) {
            loadFarm(farmId);
        } else {
            showFarmFragment(farmId);
        }
    }

    private void showFarmFragment(String farmId) {
        MainActivity ma = (MainActivity)mParent;
        ma.showFarmFragment(farmId);
    }

    private void loadFarm(String farmId) {
        mProgressForm.setVisibility(View.VISIBLE);

        String token = ((MainActivity)mParent).getToken();
        ServerRequest request = ServerRequest.newGetRequest(this, token, String.format("%s?fid=%s",PATH_LOAD_FARM, farmId));
        request.setTag("farm");
        request.execute();
    }

    public Main getMain() {
        return main;
    }
}
